<template>
  <div class="simple-test">
    <div class="test-container">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>简单后端连接测试</span>
            <el-tag type="primary">实时测试</el-tag>
          </div>
        </template>

        <div class="test-content">
          <!-- 测试按钮区域 -->
          <div class="test-buttons">
            <el-button type="primary" @click="testSendCode" :loading="loading.sendCode">
              测试发送验证码 (JSON)
            </el-button>
            <el-button type="success" @click="testSendCodeForm" :loading="loading.sendCodeForm">
              测试发送验证码 (Form)
            </el-button>
            <el-button type="warning" @click="testLogin" :loading="loading.login">
              测试登录接口
            </el-button>
            <el-button type="info" @click="testDirect" :loading="loading.direct">
              直接访问后端
            </el-button>
          </div>

          <!-- 结果显示区域 -->
          <div class="results-section">
            <h3>测试结果</h3>
            <div v-if="results.length === 0" class="no-results">
              暂无测试结果，请点击上方按钮进行测试
            </div>
            <div v-for="(result, index) in results" :key="index" class="result-item">
              <div class="result-header">
                <span class="result-time">{{ result.time }}</span>
                <el-tag :type="result.success ? 'success' : 'danger'" size="small">
                  {{ result.test }}
                </el-tag>
                <el-tag :type="getStatusType(result.status)" size="small">
                  {{ result.status }}
                </el-tag>
              </div>
              <div class="result-details">
                <p><strong>请求:</strong> {{ result.method }} {{ result.url }}</p>
                <p><strong>请求头:</strong></p>
                <pre class="json-display">{{ JSON.stringify(result.headers, null, 2) }}</pre>
                <p><strong>请求体:</strong></p>
                <pre class="json-display">{{ JSON.stringify(result.requestBody, null, 2) }}</pre>
                <p><strong>响应:</strong></p>
                <pre class="json-display">{{ JSON.stringify(result.response, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const loading = reactive({
  sendCode: false,
  sendCodeForm: false,
  login: false,
  direct: false
})

const results = ref([])

// 方法
const addResult = (test, method, url, headers, requestBody, status, response, success) => {
  results.value.unshift({
    time: new Date().toLocaleTimeString(),
    test,
    method,
    url,
    headers,
    requestBody,
    status,
    response,
    success
  })
  
  // 只保留最近10条结果
  if (results.value.length > 10) {
    results.value = results.value.slice(0, 10)
  }
}

const getStatusType = (status) => {
  if (status >= 200 && status < 300) return 'success'
  if (status >= 400 && status < 500) return 'warning'
  if (status >= 500) return 'danger'
  return 'info'
}

// 测试发送验证码 (JSON格式)
const testSendCode = async () => {
  loading.sendCode = true
  
  try {
    const requestBody = { email: '277849093@qq.com' }
    const headers = {
      'Content-Type': 'application/json'
    }
    
    const response = await fetch('/housingHub/user/send-code', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    })
    
    const responseData = await response.text()
    let parsedResponse
    try {
      parsedResponse = JSON.parse(responseData)
    } catch {
      parsedResponse = responseData
    }
    
    addResult(
      '发送验证码(JSON)',
      'POST',
      '/housingHub/user/send-code',
      headers,
      requestBody,
      response.status,
      parsedResponse,
      response.ok
    )
    
    if (response.ok) {
      ElMessage.success('发送验证码测试成功')
    } else {
      ElMessage.warning(`发送验证码测试返回: ${response.status}`)
    }
  } catch (error) {
    console.error('发送验证码测试失败:', error)
    addResult(
      '发送验证码(JSON)',
      'POST',
      '/housingHub/user/send-code',
      { 'Content-Type': 'application/json' },
      { email: '277849093@qq.com' },
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('发送验证码测试失败: ' + error.message)
  } finally {
    loading.sendCode = false
  }
}

// 测试发送验证码 (Form格式)
const testSendCodeForm = async () => {
  loading.sendCodeForm = true
  
  try {
    const formData = new FormData()
    formData.append('email', '277849093@qq.com')
    
    const headers = {}
    
    const response = await fetch('/housingHub/user/send-code', {
      method: 'POST',
      headers: headers,
      body: formData
    })
    
    const responseData = await response.text()
    let parsedResponse
    try {
      parsedResponse = JSON.parse(responseData)
    } catch {
      parsedResponse = responseData
    }
    
    addResult(
      '发送验证码(Form)',
      'POST',
      '/housingHub/user/send-code',
      headers,
      { email: '277849093@qq.com' },
      response.status,
      parsedResponse,
      response.ok
    )
    
    if (response.ok) {
      ElMessage.success('发送验证码(Form)测试成功')
    } else {
      ElMessage.warning(`发送验证码(Form)测试返回: ${response.status}`)
    }
  } catch (error) {
    console.error('发送验证码(Form)测试失败:', error)
    addResult(
      '发送验证码(Form)',
      'POST',
      '/housingHub/user/send-code',
      {},
      { email: '277849093@qq.com' },
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('发送验证码(Form)测试失败: ' + error.message)
  } finally {
    loading.sendCodeForm = false
  }
}

// 测试登录接口
const testLogin = async () => {
  loading.login = true
  
  try {
    const requestBody = {
      email: '277849093@qq.com',
      password: 'testpassword'
    }
    const headers = {
      'Content-Type': 'application/json'
    }
    
    const response = await fetch('/housingHub/user/login', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    })
    
    const responseData = await response.text()
    let parsedResponse
    try {
      parsedResponse = JSON.parse(responseData)
    } catch {
      parsedResponse = responseData
    }
    
    addResult(
      '用户登录',
      'POST',
      '/housingHub/user/login',
      headers,
      requestBody,
      response.status,
      parsedResponse,
      response.ok
    )
    
    if (response.ok) {
      ElMessage.success('登录测试成功')
    } else {
      ElMessage.warning(`登录测试返回: ${response.status}`)
    }
  } catch (error) {
    console.error('登录测试失败:', error)
    addResult(
      '用户登录',
      'POST',
      '/housingHub/user/login',
      { 'Content-Type': 'application/json' },
      { email: '277849093@qq.com', password: 'testpassword' },
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('登录测试失败: ' + error.message)
  } finally {
    loading.login = false
  }
}

// 直接访问后端
const testDirect = async () => {
  loading.direct = true
  
  try {
    const requestBody = { email: '277849093@qq.com' }
    const headers = {
      'Content-Type': 'application/json'
    }
    
    const response = await fetch('http://localhost:8085/housingHub/user/send-code', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody),
      mode: 'cors'
    })
    
    const responseData = await response.text()
    let parsedResponse
    try {
      parsedResponse = JSON.parse(responseData)
    } catch {
      parsedResponse = responseData
    }
    
    addResult(
      '直接访问后端',
      'POST',
      'http://localhost:8085/housingHub/user/send-code',
      headers,
      requestBody,
      response.status,
      parsedResponse,
      response.ok
    )
    
    if (response.ok) {
      ElMessage.success('直接访问后端成功')
    } else {
      ElMessage.warning(`直接访问后端返回: ${response.status}`)
    }
  } catch (error) {
    console.error('直接访问后端失败:', error)
    addResult(
      '直接访问后端',
      'POST',
      'http://localhost:8085/housingHub/user/send-code',
      { 'Content-Type': 'application/json' },
      { email: '277849093@qq.com' },
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('直接访问后端失败: ' + error.message)
  } finally {
    loading.direct = false
  }
}
</script>

<style scoped>
.simple-test {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.test-container {
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.test-content {
  padding: 20px 0;
}

.test-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.results-section h3 {
  color: #409eff;
  margin-bottom: 20px;
}

.no-results {
  text-align: center;
  color: #909399;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 8px;
}

.result-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.result-header {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.result-time {
  font-size: 12px;
  color: #909399;
}

.result-details p {
  margin: 10px 0;
  color: #2c3e50;
}

.json-display {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  margin: 5px 0;
}
</style>
